package com.bacon.gmall.activity.controller;

import com.bacon.gmall.activity.service.SeckillService;
import com.bacon.gmall.activity.utils.CacheHelper;
import com.bacon.gmall.activity.utils.DateUtil;
import com.bacon.gmall.common.config.RabbitConst;
import com.bacon.gmall.common.constant.RedisConst;
import com.bacon.gmall.common.result.Result;
import com.bacon.gmall.common.result.ResultCodeEnum;
import com.bacon.gmall.common.util.AuthContextHolder;
import com.bacon.gmall.common.util.MD5;
import com.bacon.gmall.common.utils.RabbitUtil;
import com.bacon.gmall.model.activity.SeckillGoods;
import com.bacon.gmall.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2021-01-13 16:49
 * @description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillController {

    //@GetMapping("/auth/getSeckillSkuIdStr/{skuId}")

    private String salt = "peigeyongyuandishen";

    @Value("${Sales.onSales}")
    public String onSales;

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitUtil rabbitUtil;

    @GetMapping("/getSeckillGoodsList")
    public List<SeckillGoods> getSeckillGoodsList() {
        return seckillService.list();
    }

    @GetMapping("/getSeckillGoods/{skuId}")
    public SeckillGoods getSeckillGoods(@PathVariable Long skuId) {
        return seckillService.getSeckillGoods(skuId);
    }

    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        SeckillGoods seckillGoods = seckillService.getSeckillGoods(skuId);

        //进行时间比较，防止在非秒杀时间购买
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Calendar instance = Calendar.getInstance();
        Date curTime = instance.getTime();

        // date1 > date2  返回：1
        // date1 = date2  返回：0
        // date1 < date2  返回：-1
        //  前面<后面=true
        if (!DateUtil.dateCompare(startTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_NO_START);
        }
        //秒杀活动活动结束
        if (DateUtil.dateCompare(endTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_END);
        }

        if (seckillGoods.getStockCount() <= 0) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }

        //审核通过
        if (!seckillGoods.getStatus().equals(onSales)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(userId + skuId + salt);

        return Result.ok(encrypt);
    }

    //开始秒杀第一阶段
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(userId + skuId + salt);

        //1、校验抢购码
        if (!encrypt.equals(skuIdStr)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //2、状态位 skuId：0
        //  本地内存
        String state = (String) CacheHelper.get(skuId.toString());
        if (!"1".equals(state)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }

        //3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setSkuId(skuId);
        userRecode.setUserId(userId);
        rabbitUtil.sendMessage(
                RabbitConst.EXCHANGE_DIRECT_SECKILL_USER,
                RabbitConst.ROUTING_SECKILL_USER,
                userRecode);

        return Result.ok();
    }


    //秒杀第二阶段
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);

        //3、用户是否来过了
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId + "skuId:" + skuId);
        if (o2 != null) {

            //1、判断是否有购买过该秒杀商品
            Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId + "skuId:" + skuId);
            if (o != null) {
                return Result.build(null, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }

            //2、查询是否有抢购资格
            Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId + "skuId:" + skuId);
            if (o1 != null) {
                return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);
            }

            return Result.build(null, ResultCodeEnum.SECKILL_RUN);
        }

        //4、状态位
        Object o3 = CacheHelper.get(skuId.toString());
        if (!"1".equals(o3)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }
        StringBuffer stringBuffer = new StringBuffer();
        StringBuilder stringBuilder = new StringBuilder();
        //排队
        return Result.build(null, ResultCodeEnum.SECKILL_RUN);
    }

}
